<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <div class="search-wrapper">
      <el-form
        v-if="queryParams.searchTypeCode == 0"
        ref="queryDataFormRef"
        :model="queryParams"
        :inline="true"
        ><el-form-item label="站点名称"
          ><el-select
            v-model="queryParams.stationsCode"
            placeholder="请选择站点名称"
            clearable
          >
            <el-option
              v-for="item in stationsList"
              :label="item.label"
              :value="item.value"
              :key="item.value"
            /> </el-select
        ></el-form-item>
        <el-form-item label="查询类型"
          ><el-select
            @change="onChangeSearchType"
            v-model="queryParams.searchTypeCode"
            placeholder="请选择查询类型"
            clearable
          >
            <el-option
              v-for="item in searchTypeList"
              :label="item.label"
              :value="item.value"
              :key="item.value"
            /> </el-select
        ></el-form-item>

        <el-form-item label="数据日期选择" prop="selectRangeTime">
          <el-date-picker
            style="width: 500px"
            v-model="queryParams.selectRangeTime"
            type="datetimerange"
            :shortcuts="shortcuts"
            range-separator="To"
            @change="rangeTimeChange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <!-- <span>{{ starttime }}---</span><span>{{ endtime }}</span> -->
          <el-button type="primary" @click="startRunSearch">开始查询</el-button>
          <!-- <el-button type="primary" @click="pauseRunSearch">暂停查询</el-button>
          <el-button type="primary" @click="contiueRunSearch"
            >继续查询</el-button
          >
          <el-button type="primary" @click="stopRunSearch">结束查询</el-button> -->
          <el-button icon="Download" type="default" @click="downLoadAllCsv"
            >下载查询数据</el-button
          >
        </el-form-item>
      </el-form>
      <el-form
        v-if="queryParams.searchTypeCode == 1"
        ref="queryChartFormRef"
        :model="queryParams"
        :inline="true"
      >
        <el-form-item label="站点名称"
          ><el-select
            v-model="queryParams.stationsCode"
            placeholder="请选择站点名称"
            clearable
          >
            <el-option
              v-for="item in stationsList"
              :label="item.label"
              :value="item.value"
              :key="item.value"
            /> </el-select
        ></el-form-item>
        <el-form-item label="查询类型"
          ><el-select
            @change="onChangeSearchType"
            v-model="queryParams.searchTypeCode"
            placeholder="请选择查询类型"
            clearable
          >
            <el-option
              v-for="item in searchTypeList"
              :label="item.label"
              :value="item.value"
              :key="item.value"
            /> </el-select
        ></el-form-item>
        <el-form-item label="曲线日期选择" prop="selectRangeTime">
          <el-date-picker
            style="width: 500px"
            v-model="queryParams.selectRangeTime"
            type="datetimerange"
            :shortcuts="shortcuts"
            range-separator="To"
            @change="rangeTimeChange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <!-- <span>{{ starttime }}---</span><span>{{ endtime }}</span> -->
          <el-button type="primary" @click="startRunChart">开始查询</el-button>
          <!-- <el-button type="primary" @click="pauseRunChart">暂停查询</el-button>
          <el-button type="primary" @click="contiueRunChart"
            >继续查询</el-button
          >
          <el-button type="primary" @click="stopRunChart">结束查询</el-button> -->
          <el-button icon="Download" type="default" @click="downLoadAllCsv"
            >下载曲线数据</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="chartcontainer">
      <el-card style="height: 100%"
        ><!-- 曲线 -->
        <el-row style="height: 100%">
          <el-col :span="4" style="height: 100%">
            <el-tree-v2
              ref="treeRef"
              style="max-width: 300px"
              :data="devInfoTreeList"
              @check-change="handleCheckChange"
              show-checkbox
              :props="props"
              :height="660"
            />
          </el-col>
          <el-col :span="20" style="height: 100%">
            <div
              Id="chartId"
              ref="chartRef"
              style="width: 100%; height: 100%"
            ></div>
          </el-col>
        </el-row>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { init } from "echarts";
import Papa from "papaparse";
import moment from "moment";
import { reactive, ref, onMounted, onUnmounted, watch, nextTick } from "vue";
import { getVoDevBaseInfoTreeApi } from "@/api/devInfo/index";
import { getFileNoPageListApi } from "@/api/file/index";
import {
  chartstop,
  chartpause,
  chartcontiue,
  chartsearch,
  uploadHistoryFile,
  getVoChartHistoryTime,
} from "@/api/trendchart/index";
import { Curve0, Curve1, Curve2, Curve3, Curve4, Curve5 } from "@/globalConf";
const treeRef = ref();
const nChartNum = ref(0);
const OrginChartDataResAr = ref([]);
const chartDateList = ref([]); //曲线时间周期
const chartDataList0 = ref([]); //曲线实时数据
const chartDataList1 = ref([]); //曲线实时数据
const chartDataList2 = ref([]); //曲线实时数据
const chartDataList3 = ref([]); //曲线实时数据
const chartDataList4 = ref([]); //曲线实时数据
const chartDataList5 = ref([]); //曲线实时数据
const props = {
  value: "id",
  label: "name",
  children: "devOneUnitPointInfoVoList",
  disabled: "disabled",
};
var barChart;
var option = {
  title: {
    text: "设备历史曲线",
  },
  tooltip: {
    trigger: "axis",
  },
  legend: {
    // data: ["Email"],
  },
  dataZoom: {
    type: "inside", //放大缩小x轴数值
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    containLabel: true,
  },
  toolbox: {
    feature: {
      saveAsImage: {},
    },
  },
  xAxis: {
    type: "category",
    boundaryGap: false,
    data: chartDateList.value,
  },
  yAxis: {
    type: "value",
  },
  series: [],
};
const InitChartBasicConf = () => {
  option.series = [];
  console.log(selectedList.value, "selectedList.value");
  selectedList.value?.forEach((ele, index) => {
    if (index == Curve0) {
      option.series.push({
        name: ele.name,
        type: "line",
        data: chartDataList0.value,
      });
    }
    if (index == Curve1) {
      option.series.push({
        name: ele.name,
        type: "line",
        data: chartDataList1.value,
      });
    }
    if (index == Curve2) {
      option.series.push({
        name: ele.name,
        type: "line",
        data: chartDataList2.value,
      });
    }
    if (index == Curve3) {
      option.series.push({
        name: ele.name,
        type: "line",
        data: chartDataList3.value,
      });
    }
    if (index == Curve4) {
      option.series.push({
        name: ele.name,
        type: "line",
        data: chartDataList4.value,
      });
    }
    if (index == Curve5) {
      option.series.push({
        name: ele.name,
        type: "line",
        data: chartDataList5.value,
      });
    }
  });
  myChart();
};
const startRunChart = () => {
  isChart.value = true;
  InitChartBasicConf();
  // stopRunSearch();
  searchRunChart();
  search();
};
const pauseRunSearch = () => {
  isChart.value = false;
  chartpause({ status: 1 }).then((res) => {});
};
const startRunSearch = () => {
  isChart.value = false;
  search();
};
const contiueRunSearch = () => {
  isChart.value = false;
  chartcontiue({ status: 0 }).then((res) => {});
};
const stopRunSearch = () => {
  isChart.value = false;
  chartstop({ status: 2 }).then((res) => {});
};
const pauseRunChart = () => {
  isChart.value = true;
  chartpause({ status: 1 }).then((res) => {});
};
const searchRunChart = () => {
  isChart.value = true;
  chartsearch({ status: 4 }).then((res) => {});
};
const contiueRunChart = () => {
  isChart.value = true;
  chartcontiue({ status: 0 }).then((res) => {});
};
const stopRunChart = () => {
  isChart.value = true;
  chartstop({ status: 2 }).then((res) => {});
};
const setChartData = () => {
  if (nChartNum.value > 0) {
    for (let index = 0; index < nChartNum.value; index++) {
      if (index == Curve0) {
        chartDataList0.value = OrginChartDataResAr.value[index]?.map(
          (it) => it.vals
        );
        chartDateList.value = OrginChartDataResAr.value[index]?.map((it) =>
          moment(it.ts).format("yyyy-MM-DD HH:mm:ss")
        );
        console.log(chartDataList0.value,"kkk");
        
        option.series[0].data = chartDataList0.value;
        option.xAxis.data = chartDateList.value;
      }
      if (index == Curve1) {
        chartDataList1.value = OrginChartDataResAr?.value[index]?.map(
          (it) => it.vals
        );
        option.series[1].data = chartDataList1.value;
      }
      if (index == Curve2) {
        chartDataList2.value = OrginChartDataResAr?.value[index]?.map(
          (it) => it.vals
        );
        option.series[2].data = chartDataList2.value;
      }
      if (index == Curve3) {
        chartDataList3.value = OrginChartDataResAr?.value[index]?.map(
          (it) => it.vals
        );
        option.series[3].data = chartDataList3.value;
      }
      if (index == Curve4) {
        chartDataList4.value = OrginChartDataResAr?.value[index]?.map(
          (it) => it.vals
        );
        option.series[4].data = chartDataList4.value;
      }
      if (index == Curve5) {
        chartDataList5.value = OrginChartDataResAr?.value[index]?.map(
          (it) => it.vals
        );
        option.series[5].data = chartDataList5.value;
      }
    }
  }
  barChart.clear;
  barChart.setOption(option,{notMerge:true});
};
const stationsList = reactive([
  {
    label: "本地场站",
    value: 0,
  },
]);
const searchTypeList = reactive([
  {
    label: "数据",
    value: 0,
  },
  {
    label: "曲线",
    value: 1,
  },
]);
const devInfoTreeList = ref([]);
const queryParams = reactive({
  selectRangeTime: null,
  devInfoCode: "",
  pointCode: "",
  startTime: null,
  endTime: null,
  stationsCode: 0,
  searchTypeCode: 1,
});
const ncurSearchType = ref(0);
const onChangeSearchType = (val) => {
  queryParams.searchTypeCode = val;
};
const myChart = () => {
  barChart = init(document.getElementById("chartId"));
  barChart.showLoading();
  barChart.setOption(option);
  window.onresize = barChart.resize;
};
const downLoadAllCsv = () => {
  fileUrls.value?.forEach((ele, index) => {
    setTimeout(() => {
      downLoadOneCsv(ele, index);
    }, index * 500); // 每个
  });
};
const downLoadOneCsv = (url, index) => {
  console.log(url);

  // 创建并点击下载链接
  const link = document.createElement("a");
  link.href = url;
  link.setAttribute("download", "filename.zip"); // 可选：指定文件名
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
const isChart = ref(true);
//查询
const search = () => {
  nChartNum.value = selectedList.value.length;
  if (nChartNum.value <= 0) {
    return;
  }
  historySelectedList.value = selectedList.value.map((ele) => ({
    startTime: queryParams.startTime,
    endTime: queryParams.endTime,
    devPointValue: ele.id,
    devPointName: ele.name,
    tableName: ele.tableName,
  }));

  getVoChartHistoryTimeByParams(historySelectedList.value);
};

//曲线历史信息
const getVoChartHistoryTimeByParams = (data) => {
  getVoChartHistoryTime(data).then((res) => {
    OrginChartDataResAr.value = res.data;
      setChartData();
      barChart.hideLoading();
      uploadHistoryDataFile();


  });
};
const fileUrls = ref([]);
//曲线数据上传
const uploadHistoryDataFile = () => {
  uploadHistoryFile().then((res) => {
    fileUrls.value = res.data;
  });
};
//获取EMS基本信息
const getVoDevBaseInfoTreeApiTree = () => {
  getVoDevBaseInfoTreeApi().then((res) => {
    devInfoTreeList.value = res.data;
  });
};
getVoDevBaseInfoTreeApiTree();
const selectedList = ref([]);
const historySelectedList = ref([]);
//树勾选事件
const handleCheckChange = (node, checked) => {
  if (checked) {
    // 当节点被选中时，将节点数据添加到列表
    selectedList.value.push({
      id: node?.id,
      name: node?.name,
      tableName: node?.devTableName,
    });
  } else {
    // 当节点被取消选中时，从列表中移除
    selectedList.value = selectedList.value.filter(
      (item) => item.id !== node.id
    );
  }
};
//时间选择
const rangeTimeChange = (date) => {
  queryParams.startTime = moment(date[0]).format("YYYY-MM-DD HH:mm:ss.SSS");
  queryParams.endTime = moment(date[1]).format("YYYY-MM-DD HH:mm:ss.SSS");
};
nextTick(() => {
  myChart();
});
onMounted(() => {});
onUnmounted(() => {});
</script>
<style lang="scss" scoped>
:deep(.dv-scroll-board .header) {
  background: #ddd !important;
}
:deep(.dv-scroll-board .rows .row-item) {
  background: gray !important;
}
.app-container {
  /* 关键：占满浏览器可视高度 */
  height: 100%;
  /* 垂直排列两层内容 */
  display: flex;
  flex-direction: column;
  /* 可选：去掉默认margin，避免页面出现滚动条 */
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  overflow: hidden; /* 禁止页面整体滚动（滚动只在内部） */
  .search-wrapper {
    max-height: 200px; /* 固定高度 */
    width: 100%;
    border-bottom: 1px solid #91d5ff;
  }
  .chartcontainer {
    /* 关键：占满页面剩余高度 */
    flex: 1;
    /* 或者用 calc 计算：页面总高度 - 第一层高度 */
    //  height: calc(100vh - 100px);
    width: 100%;
    background: #fff2e8; /* 橙色背景，方便区分 */
    padding: 16px;
    overflow: hidden;
  }
}
</style>
<style>
.chartcontainer .el-card__body {
  height: 100%;
}
</style>
